import { useState } from "react";

const BASE_URL = 'http://124.222.104.145:8003';   //后端提供的基础URL

const useApi = (path,method='GET',body=null,token=null)=>{
    const [data,setData] = useState(null);
    const [error,setError] = useState(null);
    const [loading,setLoading] = useState(false);

    const fetchData = async () => {
        setLoading(true);
        setError(null);

        try {
            const url= `${BASE_URL}${path}`;
            const options = {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                }
               };

               if(token){
                   options.headers['Authorization'] = `Bearer ${token}`;
               }

               if(body){
                   options.body = JSON.stringify(body);
               }

               const response = await fetch(url,options);
               if(!response.ok){
                   throw new Error('HTTP error! Status: ${response.status}');
               }

               const responseData = await response.json();
               setData(responseData);
        } catch (error) {
            setError(error.message);
        } finally {
            setLoading(false);
        }
    }

    return {data,error,loading,fetchData};  

}   

export default useApi;
